import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 2024-6-14 modified ：优化脚本入参
 * 2024-8-1 modified ：优化脚本，异常处理流程
 */
public class jdbc_set_get_object_case0024 {

	public static Connection GetConnection(String sourceURL, String username, String passwd) {
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(sourceURL,username,passwd);
        System.out.println("Connection succeed");
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }
    return conn;
}

/**
 * 查找数据
 */
public static void query(Connection conn) throws SQLException{
    String sql = "select current_database();";
    conn.setAutoCommit(false);
	PreparedStatement preparedStatement = null;
	ResultSet resultSet = null;
	try {
		preparedStatement = conn.prepareStatement(sql);
		resultSet = preparedStatement.executeQuery();
		System.out.println("current database is:");
		while (resultSet.next()) {
			String database = resultSet.getString("current_database");
			System.out.println(database);
		}
		conn.commit();

	} catch (SQLException e) {
		e.printStackTrace();
	}
	finally {
		resultSet.close();
		preparedStatement.close();
	}

}

public static void main(String[] args) throws SQLException {
	String urlstr = "jdbc:postgresql://" + args[0] + "/" + args[1];
	Connection conn = null;
	try {
		conn = GetConnection(urlstr, args[2], args[3]);
		query(conn);
	}
	catch (SQLException e) {
		e.printStackTrace();
	}
	finally {
		conn.close();
	}
}
}